package top.chengdongqing.mishop.common.websocket

import org.springframework.context.annotation.Configuration
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.socket.WebSocketHandler
import org.springframework.web.socket.config.annotation.EnableWebSocket
import org.springframework.web.socket.config.annotation.WebSocketConfigurer
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry
import org.springframework.web.socket.server.HandshakeInterceptor
import top.chengdongqing.mishop.order.payment.PaySuccessHandler

@Configuration
@EnableWebSocket
class WebSocketConfig(private val paySuccessHandler: PaySuccessHandler) : WebSocketConfigurer {

    override fun registerWebSocketHandlers(registry: WebSocketHandlerRegistry) {
        registry.addHandler(paySuccessHandler, "/order/payment/{orderId}")
            .setAllowedOrigins("*")
            .addInterceptors(WebSocketInterceptor())
    }

    private class WebSocketInterceptor : HandshakeInterceptor {
        override fun beforeHandshake(
            request: ServerHttpRequest,
            response: ServerHttpResponse,
            wsHandler: WebSocketHandler,
            attributes: MutableMap<String, Any>
        ): Boolean {
            val path = request.uri.path
            val lastIndex = path.lastIndexOf("/")
            val id = path.substring(lastIndex + 1)
            attributes["id"] = id
            return true
        }

        override fun afterHandshake(
            request: ServerHttpRequest,
            response: ServerHttpResponse,
            wsHandler: WebSocketHandler,
            exception: Exception?
        ) {

        }
    }
}